<?php
namespace app\common\model\mall\goods;

use think\Db;
use think\Cookie;
use think\Hook;

/**
 * 购物车
 */

class Cart extends \think\Model
{
    protected $name = 'mall_goods_cart';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 追加属性
    protected $append = [

    ];

    /**
     * 获取购物车商品列表
     */
    public function getCartInfo($isSettlement = false){
        $user_id = (int)Cookie::get('uid');
        $where = [];
        $where['c.user_id'] = $user_id;
        if($isSettlement) $where['c.checkis'] = 1;
        $rs = $this->alias('c')
            ->join('__MALL_GOODS_GOODS__ g','c.goods_id=g.id','inner')
            ->join('__MALL_GOODS_SALESPEC__ gs','c.salespec_id=gs.id','left')
            ->where($where)
            ->field('c.salespec_id,c.id,c.goods_id,g.goodsname,g.shopprice,g.goodsstock,g.specis,gs.specprice,gs.specstock,g.goodsimg,c.checkis,gs.specitem_ids,c.num')
            ->select();
        $goods_ids = [];
        $goodsTotalMoney = 0;
        //$goodsTotalNum = 0;
        foreach ($rs as $key =>$v){
            if(!in_array($v['id'],$goods_ids)) $goods_ids[] = $v['id'];
            if($v['specis']==1){
                $v['shopprice'] = $v['specprice'];
                $v['goodsstock'] = $v['specstock'];
            }
            if($v['goodsstock']<$v['num']){
                $v['num'] = $v['goodsstock'];
            }
            $goodsTotalMoney = $goodsTotalMoney + $v['shopprice'] * $v['num'];
        }
        //加载规格值
        if(count($goods_ids)>0){
            $specs = Db::name('mall_goods_specitem')->alias('s')
                ->join('__MALL_GOODS_CATSPEC__ sc','s.spec_id=sc.id','left')
                ->where('s.goods_id','in',$goods_ids)
                ->field('itemId,itemname')->select();
            if(count($specs)>0){
                $specMap = [];
                foreach ($specs as $key =>$v){
                    $specMap[$v['itemId']] = $v;
                }
                foreach ($rs as $key =>$v){
                    $strName = [];
                    if($v['specitem_ids']!=''){
                        $str = explode(':',$v['specitem_ids']);
                        foreach ($str as $vv){
                            if(isset($specMap[$vv]))$strName[] = $specMap[$vv]['itemname'];
                        }
                    }
                    $rs[$key]['specNames'] = $strName;
                }
            }
        }
        $goodsTotalNum = count($rs);
        $cartData = [
            'list'=>$rs,
            'goodsTotalMoney'=>sprintf("%.2f", $goodsTotalMoney),
            'goodsTotalNum'=>$goodsTotalNum
        ];
        return $cartData;
    }

    /**
     * 获取购物车列表
     * @param bool $isSettlement 是否结算
     * @return array
     */
    public static function getCartList($isSettlement = false){
        $where = [];
        $where["c.user_id"] = cookie('uid');
        //如果是结算调用，则仅获取选中的商品；如果是查看，则显示所有购物车商品
        if($isSettlement) $where["c.checkis"] = 1;
        $list = self::alias('c')
            ->join('__MALL_GOODS_GOODS__ g','c.goods_id=g.id','inner')
            ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id','inner')
            ->join('__MALL_GOODS_SALESPEC__ gs','c.salespec_id=gs.id','left')
            ->field('c.id,s.user_id,g.shop_id,s.name,s.freight shopfreight,s.shopQQ,s.shopWangWang,
                c.goods_id,g.goodsimg,
                g.goodsname,g.shopprice,g.goodsstock,g.specis,g.goodscat_ids,g.freighttype,g.weight,
                g.goodstype,c.salespec_id,gs.specprice,gs.specstock,c.checkis,gs.specitem_ids,
                c.num,case when g.specis=1 then gs.specprice else g.shopprice end * c.num total')
            ->where($where)
            ->order("g.shop_id,c.id")
            ->select();

        //购物车分组计算;
        $cart = [];
        //购物车商品数
        $cart['cart_goods_num'] = count($list);
        //购物车店铺总金额
        $cart_shop_price = [];
        foreach ($list as $val) {
            if($val['specis']){
                $val['shopprice'] = $val['specprice'];
                $val['goodsstock'] = $val['specstock'];
            }
            if(!isset($cart_shop_price[$val["shop_id"]]))
                $cart_shop_price[$val["shop_id"]] = 0;
            //将选中商品进行累计
            if($val["checkis"]) {
                $cart_shop_price[$val["shop_id"]] += $val['total'];
            }
        }
        $cart['cart_shop_price'] = $cart_shop_price;
        //购物车总金额
        $cart['cart_all_price'] = array_sum($cart_shop_price);

        //整理数据，准备渲染到前端
        $goods_ids = array_column($list,"goods_id");
        foreach ($list as $val) {
            $specs = [];
            if ($val['specis']) {
                $val['shopprice'] = $val['specprice'];
                $val['goodsstock'] = $val['specstock'];
                if (!$val["goodstype"]) {
                    $specitem_ids = str_replace(':', ',', $val['specitem_ids']);
                    $specs = Db::name('mall_goods_specitem')->alias('s')
                        ->join('__MALL_GOODS_CATSPEC__ cs', 's.spec_id=cs.id', 'left')
                        ->where('s.goods_id', 'in', $goods_ids)
                        ->where('', 'EXP', Db::raw('FIND_IN_SET(s.itemId,"' . $specitem_ids . '")'))
                        ->field('cs.specname, s.itemname')->select();
                    foreach ($specs as $k => $v) {
                        $temp = $v['specname'] . ':' . $v['itemname'];
                        $specs[$k] = $temp;
                    }
                }
            }
            $val['goodsspecs'] = $specs;
            $val['shoptotal'] = [["title" => "店铺合计", "value" => number_format($cart['cart_shop_price'][$val['shop_id']], 2)]];
            $val['carttotal'] = [["title" => "总计", "value" => number_format($cart['cart_all_price'], 2)]];
        }

        return $list;
    }


    /**
     * 获取session中购物车列表
     */
    public static function getVisitorCart($num = 0){
        $tmp_carts = session('TMP_CARTS');
        $where = [];
        $where['g.id'] = ["in",$tmp_carts['goods_id']];
        $num = $num>0 ? $num : $tmp_carts['num'];
        $salespec_id = $tmp_carts['salespec_id'];
        $goodstype = $tmp_carts['goodstype'];
        $list = Db::name('mall_goods_goods')->alias('g')
            ->join('__MALL_SHOP_SHOP__ s','g.shop_id=s.id','left')
            ->join('__MALL_GOODS_SALESPEC__ gs',$salespec_id.'=gs.id','left')
            ->field('s.user_id,g.shop_id,s.name,s.freight shopfreight,s.shopQQ,s.shopWangWang,
                g.id goods_id,g.goodsimg,
                g.goodsname,g.shopprice,g.goodsstock,g.specis,g.goodscat_ids,g.freighttype,g.weight,
                g.goodstype,gs.specprice,gs.specstock,gs.specitem_ids,'.$salespec_id.' salespec_id,'.
                $num.' num,case when g.specis=1 then gs.specprice else g.shopprice end * '.$num.' total')
            ->where($where)
            ->order("g.shop_id,g.id")
            ->select();

        //购物车分组计算;
        $cart = [];
        //购物车商品数
        $cart['cart_goods_num'] = count($list);
        //购物车店铺总金额
        $cart_shop_price = [];
        foreach ($list as $val) {
            if($val['specis']){
                $val['shopprice'] = $val['specprice'];
                $val['goodsstock'] = $val['specstock'];
            }
            if(!isset($cart_shop_price[$val["shop_id"]]))
                $cart_shop_price[$val["shop_id"]] = 0;

            $val['total'] = $val['shopprice']*$val['num'];
            $cart_shop_price[$val["shop_id"]] += $val['total'];
        }
        $cart['cart_shop_price'] = $cart_shop_price;
        //购物车总金额
        $cart['cart_all_price'] = array_sum($cart_shop_price);

        //整理数据，准备渲染到前端
        $goods_ids = array_column($list,"goods_id");
        foreach ($list as $key=>$val) {
            $specs = [];
            if ($val['specis']) {
                $val['shopprice'] = $val['specprice'];
                $val['goodsstock'] = $val['specstock'];
                if (!$val["goodstype"]) {
                    $specitem_ids = str_replace(':', ',', $val['specitem_ids']);
                    $specs = Db::name('mall_goods_specitem')->alias('s')
                        ->join('__MALL_GOODS_CATSPEC__ cs', 's.spec_id=cs.id', 'left')
                        ->where('s.goods_id', 'in', $goods_ids)
                        ->where('', 'EXP', Db::raw('FIND_IN_SET(s.itemId,"' . $specitem_ids . '")'))
                        ->field('cs.specname, s.itemname')->select();
                    foreach ($specs as $k => $v) {
                        $temp = $v['specname'] . ':' . $v['itemname'];
                        $specs[$k] = $temp;
                    }
                }
            }
            $list[$key]['goodsspecs'] = $specs;
            $list[$key]['shoptotal'] = [["title" => "店铺合计", "value" => number_format($cart['cart_shop_price'][$val['shop_id']], 2)]];
            $list[$key]['carttotal'] = [["title" => "总计", "value" => number_format($cart['cart_all_price'], 2)]];
        }

        return $list;
    }

}
